package com.skit.mine.fragment;

import android.app.ProgressDialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.skit.common.ResourcesManager;
import com.skit.common.bean.StatusResult;
import com.skit.common.bean.User;
import com.skit.common.bean.UserInfo;
import com.skit.common.config.RetrofitClient;
import com.skit.common.http.HttpUtils;
import com.skit.common.manager.UserManager;
import com.skit.common.utils.ToastUtils;
import com.skit.mine.R;
import com.skit.mine.adapter.SingleTextStringAdapter;
import com.skit.common.retrofit.UserProtocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since 2020/5/23
 */

public class EthnicBottomSheetFragment extends BottomSheetDialogFragment {
    private static final String TAG = "DepartmentBottomSheetFr";
    private RecyclerView recyclerView, recyclerView2;
    private SingleTextStringAdapter adapter;

    private List<String> list = new ArrayList<>();
    private Handler handler = new Handler();
    private ImageView back;
    private TextView title;
    private OnFinishListener onFinishListener;

    public interface OnFinishListener {
        void onFinish();
    }

    public void setOnFinishListener(OnFinishListener onFinishListener) {
        this.onFinishListener = onFinishListener;
    }

    public static EthnicBottomSheetFragment newInstance() {

        Bundle args = new Bundle();

        EthnicBottomSheetFragment fragment = new EthnicBottomSheetFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.user_bottom_sheet_dialog_layout, container, false);
        recyclerView = inflate.findViewById(R.id.recyclerView);
        recyclerView2 = inflate.findViewById(R.id.recyclerView2);
        back = inflate.findViewById(R.id.back);
        title = inflate.findViewById(R.id.title);
        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        title.setText(getTag());
        User user = UserManager.getUser();
        if (user == null) {
            dismiss();
            return;
        }
        adapter = new SingleTextStringAdapter(list);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener((data, position) -> {
            setData(data, user);
        });

        back.setOnClickListener(v -> {
            title.setText("学院");
            if (recyclerView.getVisibility() == View.VISIBLE) {
                dismiss();
            } else {
                recyclerView.setVisibility(View.VISIBLE);
                recyclerView2.setVisibility(View.GONE);
            }
        });

        new Thread(this::read).start();
    }

    private void setData(String ethnic, User user) {
        ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("正在请求。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("ethnic", ethnic);
        String s = new Gson().toJson(map);
        UserProtocol userProtocol = RetrofitClient.getService(UserProtocol.class);
        Call<StatusResult<String>> update = userProtocol.update(user.getToken(), user.getId(), "ethnic", s);
        HttpUtils.doRequest(update, result -> {
            progressDialog.dismiss();
            if (result == null || !result.isSuccess()) {
                if (result != null) ToastUtils.showToast(result.getMsg());
                dismiss();
                return;
            }

            UserInfo userInfo = user.getUserInfo();
            userInfo.setEthnic(ethnic);
            UserManager.saveUser(user);
            dismiss();
            if (onFinishListener != null) {
                onFinishListener.onFinish();
            }

        });
    }

    private void read() {
        AssetManager assetManager = ResourcesManager.getRes().getAssets();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open("ethnic.json"), StandardCharsets.UTF_8));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            bufferedReader.close();
            String string = stringBuilder.toString();
            List<Ethnic> ethnicList = new Gson().fromJson(string, new TypeToken<List<Ethnic>>() {
            }.getType());

            getActivity().runOnUiThread(() -> {
                Log.d(TAG, "read: ");
                for (Ethnic ethnic : ethnicList) {
                    list.add(ethnic.getName());
                }
                adapter.notifyDataSetChanged();
            });
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "read: ", e);
        }
    }

    static class Ethnic {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}
